package com.example.abe.diandi.trends.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.example.BindView;
import com.example.abe.diandi.R;
import com.example.abe.diandi.base.BaseFragment;
import com.example.abe.diandi.category.model.CategoryModel;
import com.example.abe.diandi.common.CommonHeaderView;
import com.example.abe.diandi.nohttp.ApiUtil;
import com.example.abe.diandi.nohttp.CallServer;
import com.example.abe.diandi.nohttp.HttpListener;
import com.example.abe.diandi.trends.activity.TrendsShowActivity;
import com.example.abe.diandi.trends.adapter.BaseTrendsDelegate;
import com.example.abe.diandi.trends.adapter.ImageTextTrendsDelegate;
import com.example.abe.diandi.trends.adapter.ImageTrendsDelegate;
import com.example.abe.diandi.trends.adapter.TextTrendsDelegate;
import com.example.abe.diandi.trends.model.TrendListModel;
import com.example.abe.diandi.trends.model.TrendModel;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.List;

import example.abe.com.framework.recycleview.adapter.BaseAdapter;
import example.abe.com.framework.refresh.OnLoadMoreListener;
import example.abe.com.framework.refresh.OnRefreshListener;
import example.abe.com.framework.refresh.SwipeToLoadLayout;
import example.abe.com.framework.util.TimeUtil;
import example.abe.com.framework.util.ToastUtil;

import static com.example.abe.diandi.nohttp.ApiUtil.METHOD;
import static com.example.abe.diandi.nohttp.ApiUtil.M_TREND_GET_TRENDS_LIST_BY_CATEGORY;
import static com.example.abe.diandi.nohttp.ApiUtil.SERVICE;
import static com.example.abe.diandi.nohttp.ApiUtil.S_TREND;

/**
 * Created by abe on 17/1/12.
 */
public class TrendsFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.swipe_target)
    protected RecyclerView mRv;

    @BindView(R.id.swipe_refresh_header)
    protected CommonHeaderView mHeaderView;

    @BindView(R.id.swipe_load_more_footer)
    protected CommonHeaderView mFooterView;

    @BindView(R.id.frag_trends_swipe_to_load)
    protected SwipeToLoadLayout mSwipeToLoadLayout;

    private CategoryModel mCategoryModel;

    private BaseAdapter<TrendModel> mAdapter;

    private List<TrendModel> mListData;

    private String mStartTrendId;

    public static TrendsFragment instance() {
        return new TrendsFragment();
    }

    @Override
    public int getLayoutID() {
        return R.layout.fragment_trends;
    }

    @Override
    public void initData() {
        mListData = new ArrayList<>();
        mStartTrendId = "-1";
    }

    @Override
    public void initView() {
        mSwipeToLoadLayout.setOnRefreshListener(this);
        mSwipeToLoadLayout.setOnLoadMoreListener(this);

        mAdapter = new BaseAdapter<>(getContext(), mListData);
        mAdapter.addItemViewDelegate(new TextTrendsDelegate(onItemClickListener));
        mAdapter.addItemViewDelegate(new ImageTrendsDelegate(onItemClickListener));
        mAdapter.addItemViewDelegate(new ImageTextTrendsDelegate(onItemClickListener));
        mRv.setLayoutManager(new LinearLayoutManager(getContext()));
        mRv.setAdapter(mAdapter);

        mSwipeToLoadLayout.setRefreshing(true);
    }

    @Override
    public void onResume(){
        super.onResume();
    }

    public void setCategoryModel(CategoryModel mCategoryModel) {
        this.mCategoryModel = mCategoryModel;
    }

    public void setStartRefresh() {
        mSwipeToLoadLayout.setRefreshing(true);
    }

    private BaseTrendsDelegate.OnClickListener onItemClickListener = new BaseTrendsDelegate.OnClickListener() {
        @Override
        public void onClick(View v, int position) {
            Intent intent = new Intent(getContext(), TrendsShowActivity.class);
            intent.putExtra(TrendsShowActivity.NOTE_MODEL_DATA, mListData.get(position));
            startActivity(intent);
        }
    };

    @Override
    public void onRefresh() {
        mStartTrendId = "-1";
        mListData.clear();
        updateTrendList(mCategoryModel.getId(), mStartTrendId);
    }

    @Override
    public void onLoadMore() {
        mStartTrendId = mListData.get(mListData.size()-1).getId();
        updateTrendList(mCategoryModel.getId(), mStartTrendId);
    }

    private void updateTrendList(String categoryId, String startTrendId){
        Request<String> request = NoHttp.createStringRequest(ApiUtil.URL, RequestMethod.POST);
        request.add(SERVICE, S_TREND)
                .add(METHOD, M_TREND_GET_TRENDS_LIST_BY_CATEGORY)
                .add("categoryId", categoryId)
                .add("startTrendId", startTrendId)
                .add("limit", 10);
        CallServer.getInstance().add(getActivity(), false, request, new HttpListener<String>() {

            @Override
            public void onSucceed(int what, Response<String> response) {
                JsonObject jsonObj = new JsonParser().parse(response.get()).getAsJsonObject();
                Boolean isSuccess = jsonObj.get("success").getAsBoolean();
                if (isSuccess) {
                    JsonObject data = jsonObj.getAsJsonObject("data");
                    TrendListModel model = new Gson().fromJson(data, TrendListModel.class);
                    mListData.addAll(model.getList());
                    reInitListData();
                    mAdapter.notifyDataSetChanged();
                }
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                ToastUtil.makeText("加载失败");
            }
        });
    }

    /**
     * 重构数据
     */
    private void reInitListData(){
        String time = "";
        for (TrendModel model: mListData){
            String temp = TimeUtil.getStrTimeCH(model.getTime(), TimeUtil.FORMAT_YYYYMMDD);
            if (time.equals(temp)){
                model.setDayFirst(false);
            }else {
                model.setDayFirst(true);
                time = temp;
            }
        }
    }
}
